package com.fzrskj.cloud.free.thridparty.pay.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.PayTypeEnum;
import com.fzrskj.cloud.free.core.enums.PayWayEnum;
import com.fzrskj.cloud.free.core.tool.CStrTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.user.bean.UserCharge;
import com.fzrskj.cloud.free.user.utils.UserChargeUtils;
import com.winiis.component.pay.wechat.core.QrCodePay;
import ms.core.consts.SysErr;
import ms.core.tool.DateTimeTool;
import ms.core.tool.StrTool;
import org.apache.commons.collections.map.HashedMap;

import java.util.Date;
import java.util.Map;

/**
 * WechatPay.
 *
 * @author zj.
 *         Created on 2018/12/29 0029.
 */
public class WechatPay {
    //private static QrCodePay qrCodePay;
    /**
     * 微信支付.
     */
    private static Map<Integer, QrCodePay> qrCodePay = new HashedMap();

    /**
     * 初始化.
     */
    public static void init() {
        if ("1".equals(DicParamUtils.getParamValue(DicParamEnum.WECHAT_PAY_IS_OPEN.getVal()))) {
            if (!qrCodePay.containsKey(CloudContextUtils.getAgentId())) {
                qrCodePay.put(CloudContextUtils.getAgentId(), new QrCodePay(new WechatPayConfig(), new WechatPaySuccessImpl(), new WechatPayLogImpl()));
            }
        }
    }

    /**
     * 获取.
     * @return
     */
    public static QrCodePay getQrCodePay() {
        if (qrCodePay.containsKey(CloudContextUtils.getAgentId())) {
            qrCodePay.put(CloudContextUtils.getAgentId(), new QrCodePay(new WechatPayConfig(), new WechatPaySuccessImpl(), new WechatPayLogImpl()));
        }
        return qrCodePay.containsKey(CloudContextUtils.getAgentId()) ? qrCodePay.get(CloudContextUtils.getAgentId()) : null;
    }

    /**
     * 创建微信支付订单.
     * @param paramString {"amount":53,"uid":100000,"uname":"lsyfg","Ip":"0:0:0:0:0:0:0:1","email":"lsyfg"}
     * @return
     */
    public static String create(String paramString) {
        //初始化微信参数.
        init();

        JSONObject param = JSONObject.parseObject(paramString);
        JSONObject result = new JSONObject();
        String userName = param.containsKey("uname") ? param.getString("uname") : "";
        Integer userId = param.containsKey("uid") ? param.getInteger("uid") : 0;
        Double amount = param.containsKey("amount") ? param.getDouble("amount") : 0;
        String bizOrderId = param.containsKey("orderId") ? param.getString("orderId") : "";
        if (StrTool.isBlankStr(userName) || userId < 1 || amount <= 0) {
            result.put("code", "-1");
            result.put("message", "支付参数错误：" + paramString);
            return JSON.toJSONString(result);
        }
        String orderId = createOrder();

        Integer fromAgentId = CloudContextUtils.getAgentId();
        String way = DicParamUtils.getParamValue(PayWayEnum.WECHAT.getKey());
        if ("99".equals(way)) {
            fromAgentId = DicParamUtils.getLastSelfPayParent(PayWayEnum.WECHAT.getKey(), fromAgentId);
        }

        // 插入充值记录
        UserCharge userCharge = new UserCharge();
        userCharge.setUserName(userName);
        userCharge.setUserId(userId);
        userCharge.setAmount(amount);
        userCharge.setBankCode(PayTypeEnum.WXPAY.getTag());
        userCharge.setStatus("N");
        userCharge.setOrderId(orderId);
        userCharge.setRegTime(new Date());
        userCharge.setBizOrderId(bizOrderId);
        UserChargeUtils userChargeUtils = new UserChargeUtils();
        userChargeUtils.addUserCharge(userCharge);
        userCharge.setFromAgentUserId(fromAgentId);
        String code = userChargeUtils.getErrCode();
        userChargeUtils.dispose();
        if (!code.equals(SysErr.CODE_SUCCESS)) {
            result.put("code", "-1");
            result.put("message", "充值失败,无法添加充值记录。");
            return JSON.toJSONString(result);
        }
        result.put("code", "1");
        result.put("message", "添加充值订单成功");
        result.put("paychannel", PayTypeEnum.WXPAY.getTag());
        result.put("orderid", orderId);
        return JSON.toJSONString(result);
    }

    /**
     * 创建支付订单编号.
     * @return
     */
    private static String createOrder() {
        String date = DateTimeTool.formatDateTime(new Date(), "yyyyMMddHHmmss");
        return "WX" + date + "_" + CStrTool.randNum(6) + "_" + CloudContextUtils.getAgentId();
    }
}
